package com.ddyx.util;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

import org.springframework.util.StringUtils;

/**
 * @ClassName:  ImageUtils   
 * @Description:图片工具类 
 * @author: JiangShuai 
 * @date:   2017年12月21日 下午8:55:24     
 * @Copyright: 2017 dingdian.parllay.cn Inc. All rights reserved. 
 * 注意：本内容仅限于叮当一下(北京)信息技术有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
public class ImageUtils {
	
    /**
     * @Title: getMd5ByFile   
     * @Description: 获取文件MD5 
     * @author: JiangShuai
     * @param: @param file
     * @param: @return
     * @param: @throws FileNotFoundException      
     * @return: String
     */
    public static String getMd5ByFile(File file) throws FileNotFoundException {  
        String value = null;  
        FileInputStream in = new FileInputStream(file);  
	    try {  
	        MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());  
	        MessageDigest md5 = MessageDigest.getInstance("MD5");  
	        md5.update(byteBuffer);  
	        BigInteger bi = new BigInteger(1, md5.digest());  
	        value = bi.toString(16);  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    } finally {  
	            if(null != in) {  
	                try {  
	                in.close();  
	            } catch (IOException e) {  
	                e.printStackTrace();  
	            }  
	        }  
	    }  
	    return value;  
    }
	
	/**
	 * @Title: getImage   
	 * @Description: 网络图片下载到本地 
	 * @param: @param urlstr       savePath  保存路径
	 * @return: void
	 */
	public static void getImage(String urlstr,String savePath,String imageName) {
		if(StringUtils.hasText(urlstr) && StringUtils.hasText(savePath) && StringUtils.hasText(imageName)) {
			int in=getState(urlstr);
			if(200==in) {
				URL url = null;
				try {
					url = new URL(urlstr);
					DataInputStream dataInputStream = new DataInputStream(url.openStream());
					//创建路径
					QRCodeUtil.mkdirs(savePath);
			        
					File file = new File(savePath+imageName);
			        FileOutputStream fileOutputStream = new FileOutputStream(file);
			        ByteArrayOutputStream output = new ByteArrayOutputStream();

			        byte[] buffer = new byte[1024];
			        int length;
			        while ((length = dataInputStream.read(buffer)) > 0) {
			            output.write(buffer, 0, length);
			        }
			        fileOutputStream.write(output.toByteArray());
			        dataInputStream.close();
			        fileOutputStream.close();
			    } catch (MalformedURLException e) {
			        e.printStackTrace();
			    } catch (IOException e) {
			        e.printStackTrace();
			    }
			}
		}
	}
	
	/**
	 * @Title: getState   
	 * @Description: 判断网络上的图片是否存在
	 * @param: @param url 路径
	 * @param: @return      
	 * @return: Integer 200为存在 其他不存在
	 */
	public static Integer getState(String url) {
		if(!StringUtils.hasText(url)) {
			return 101;
		}
		HttpURLConnection connection;
		try {
			URL ur = new URL(url);
			connection = (HttpURLConnection) ur.openConnection();
			int state = connection.getResponseCode();  
			System.out.println(state);
			return state;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 101;
	}
	
	/**
	 * @Title: recurDelete   
	 * @Description: 删除当前路径所有文件及该文件夹
	 * @param: @param f      
	 * @return: void
	 */
	public static void recurDelete(File f){  
	    try{  
	    	for(File fi:f.listFiles()){  
	    		if(fi.isDirectory()){  
		            recurDelete(fi);  
		        }else{  
		            fi.delete();  
		        }  
		    }  
	    	f.delete();  
	    }catch(NullPointerException n){  
	    	n.printStackTrace(); 
	    }  
	}  
	
//	public static void main(String[] args) {
//		String url="http://dingdian.parllay.cn/resource/B02S0002/8/8.jpg";
//		String savePath=PropertiesUtil.getProperty("QRCode.logo");
//		String imageName =  "logo1.jpg";
//	    // 获取开始时间  
//        long startTime = System.currentTimeMillis();  
//        
//        getState(url);
//        getImage(url,savePath,imageName);
//        System.out.println("图片保存成功");
//        try {
//			Thread.sleep(5000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//        
//        new File(savePath+imageName).delete();
//        //获取结束时间  
//        long endTime=System.currentTimeMillis();  
//        
//        System.out.println("程序运行时间： "+(endTime - startTime)+"ms");  
//	}
}
